<template>
  <div class="taskcreatecom">
    <div class="searchcondition resultlist">
      <el-scrollbar>
        <el-form label-width="auto" style="">
          <el-form-item label="名称">
            <el-input
              v-model="sousuoparams.mingcheng"
              placeholder=""
              size="normal"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="区域">
            <quyufanweicom :fenfaparams="sousuoparams" />
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="sousuoparams.shijianfanwei"
              type="daterange"
              start-placeholder="开始"
              end-placeholder="结束"
              value-format="YYYY-MM-DD"
              :default-value="[new Date(2015, 1, 1), new Date(2030, 1, 1)]"
            />
          </el-form-item>
          <el-form-item label="分辨率">
            <cengjisearch :fenfaparams="sousuoparams" />
          </el-form-item>
          <!-- <el-form-item label="传感器">
            <el-checkbox-group v-model="sousuoparams.chuanganqi">
              <el-checkbox :label="item" :value="item" v-for="item in chuanganqiopts" />
            </el-checkbox-group>
          </el-form-item> -->
        </el-form>
        <!-- {{sousuoparams}} -->
        <div style="padding: 5px 0px">
          <el-button
            type="primary"
            size="default"
            style="width: 100%"
            @click="searchClick()"
            >搜索</el-button
          >
        </div>

        <div class="searchcondition">
          <div
            class="searchcondition fr searchresultitem"
            style="justify-content: space-between"
            v-for="item in dataList"
            @mouseover="handleMouseOver(item)"
            @mouseout="handleMouseOut(item)"
          >
            <div style="position: absolute; top: 3px; left: 5px">
              <el-image
                style="width: 40px; height: 40px"
                class="custom-thumbnail"
                :src="
                  '/api/suoluetu/' + encodeURIComponent(item.thumbnail.split('/').pop())
                "
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :hide-on-click-modal="true"
                :preview-teleported="true"
                :preview-src-list="[
                  '/api/suoluetu/' + encodeURIComponent(item.thumbnail.split('/').pop()),
                ]"
                :initial-index="4"
                fit="cover"
              />
            </div>
            <div style="cursor: pointer" @click="nameClick(item)">
              &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

              <el-popover placement="left" :width="400" offset="65" trigger="hover">
                <template #reference>
                  {{ item.name }}
                </template>
                <el-descriptions
                  class="margin-top"
                  title="详细信息"
                  :column="1"
                  :size="size"
                  border
                >
                  <el-descriptions-item >
                    <template #label>
                      名称
                    </template>
                    {{item.name}}
                  </el-descriptions-item>
                  <el-descriptions-item >
                    <template #label>
                      扩展信息
                    </template>
                    {{item.desc}}
                  </el-descriptions-item>
                  <el-descriptions-item >
                    <template #label>
                      影像时间
                    </template>
                    {{item.imgtime}}
                  </el-descriptions-item>
                  <el-descriptions-item >
                    <template #label>
                      影像路径
                    </template>
                    {{item.imgpath}}
                  </el-descriptions-item>
                  <el-descriptions-item >
                    <template #label>
                      入库时间
                    </template>
                    {{item.imgtime}}
                  </el-descriptions-item>
                  <el-descriptions-item >
                    <template #label>
                      面积大小
                    </template>
                    {{}}50km²
                  </el-descriptions-item>
                  </el-descriptions
                >
              </el-popover>

              <!-- {{ item.desc + "/" + item.name + "/" + item.imgtime }} -->
            </div>
            <div class="fb" style="width: 80px">
              <div @click="viewClick(item)">
                <el-icon style="cursor: pointer; font-size: 20px"><View /></el-icon>
              </div>
              <div @click="addTmpClick(item)">
                <el-icon style="cursor: pointer; font-size: 20px"><FolderAdd /> </el-icon>
              </div>
              <div @click="downloadClick(item)">
                <el-icon style="cursor: pointer; font-size: 20px"><Download /></el-icon>
              </div>
            </div>
          </div>
          <div
            v-if="dataList.length != 0"
            class="frcc"
            style="background-color: #555a; border-radius: 5px"
          >
            <el-pagination
              v-model:current-page="pageNum"
              @current-change="loadData()"
              size="small"
              layout="prev, pager, next, total"
              :page-size="pageSize"
              :total="totalCount"
            ></el-pagination>
          </div>
          <div v-if="dataList.length == 0" class="frcc">搜索结果为空</div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, watch } from "vue";
import { useWebSocket } from "@vueuse/core";
import { httpRequest } from "@/api/httpRequest";
import { useEarthStore } from "@/stores/earth";
import _ from "lodash";
import { reactive } from "vue";
import dayjs from "dayjs";
import { apiList } from "@/api/apiList";

// import fengecom from "./common/fengefangshi.vue";
import quyufanweicom from "../serviceFf/common/quyufanwei.vue";

import useCommon from "@/components/pages/shujuguanli/common/useCommon.js";

let Common = useCommon();

const earthStore = useEarthStore();
let searchparams = reactive({});

let pageSize = ref(10);
let totalCount = ref(10000);
let pageNum = ref(1);

let sousuoparams = reactive({
  mingcheng: "",
  cengji: [],
  quyufanwei: "",
  quyufanweival: [],
  shijianfanwei: [],
  chuanganqi: [],
});

let chuanganqiopts = ref([]);

let dataList = ref([]);

// function viewClick(params) {
//   Common.removeAll();
//   Common.loadLinesearch(params);
// }

let hoveritem = "";
let allelist = [];

function nameClick(params) {
  allelist.map(item => {
    if (item.id == params.item.id) {
      viewer.flyTo(item, {
        duration: 0.2,
      });
    }
  });
}

function addTmpClick(iitem) {
  // 添加到临时图层
  if (!_.has(earthStore.pannellist, "rollerpannel")) {
    earthStore.pannellist["rollerpannel"] = {
      name: "roller-pannel",
      options: {},
    };
    setTimeout(() => {
      // window.rollercom

      window.rollercom.exposed.addimage(iitem);
    }, 500);
  } else {
    window.rollercom.exposed.addimage(iitem);
  }
}

function downloadClick(item) {
  const fileUrl = `/api/download?file=${encodeURIComponent(item.imgpath)}`;
  // const fileUrl = 'http://localhost:3000/api/download?file=your/file/directory/example-large-file.pdf';
  const link = document.createElement("a");
  link.href = fileUrl;
  // link.setAttribute("download", "example-large-file.pdf"); // 可选
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link); // 清理 DOM
}
function downloadClick1(item) {
  console.log(item);
  apiList.shujuguanli.getdownload(item.imgpath).then(res => {
    // 创建一个下载链接并触发下载
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "example-large-file.pdf"); // 设置默认下载的文件名
    document.body.appendChild(link);
    link.click();

    // 释放 URL 对象
    window.URL.revokeObjectURL(url);
  });
}

// loadTif
function viewClick(params) {
  Common.removeAll();
  Common.loadTif(params, false);
}

function handleMouseOver(params) {
  if (hoveritem != params.item.id) {
    // 取消高亮并重新设置

    if (hoveritem != "") {
      allelist.map(item => {
        if (item.id == hoveritem) {
          console.log();
          item.polygon.outlineColor = Cesium.Color.fromCssColorString("#00ffff");
          item.polygon.material = Cesium.Color.fromCssColorString("#00ff0000");
        }
      });
    }

    hoveritem = params.id;
    allelist.map(item => {
      if (item.id == params.item.id) {
        console.log(item);
        item.polygon.outlineColor = Cesium.Color.fromCssColorString("#00ff0055");
        item.polygon.material = Cesium.Color.fromCssColorString("#00ff0055");
      }
    });
  }
}
function handleMouseOut(params) {
  hoveritem = "";
  allelist.map(item => {
    if (item.id == params.item.id) {
      item.polygon.outlineColor = Cesium.Color.fromCssColorString("#00ffff");
      item.polygon.material = Cesium.Color.fromCssColorString("#00ff0000");
    }
  });
}

let cqlsearchparams = {};

function searchClick() {
  // let params = {
  //     "timeRange": "2018-08-01:2019-07-10",//时间范围（:分隔）
  //     "sensor": "WV02,GE01",//传感器（,分隔）
  //     "wxName": "卫星",//卫星名称
  //     "sunCorner": "",//太阳角
  //     "geojson": [
  //         "121.268038 24.706764,121.413084 24.706270,121.412428 24.555461,121.245265 24.555650,121.268038 24.706764",
  //         "121.268038 24.706764,121.413084 24.706270,121.412428 24.555461,121.250265 24.555650,121.268038 24.706764"
  //     ],//矩形框四角点
  //     "shpPath": "",//矢量文件导入
  //     "level": ""//分辨率
  // }

  let params = {
    timeRange: "", //时间范围（:分隔）
    sensor: "", //传感器（,分隔）
    wxName: "", //卫星名称
    sunCorner: "", //太阳角
    geojson: [], //矩形框四角点
    shpPath: "", //矢量文件导入
    level: "", //分辨率
  };

  let cqlstr = "";

  console.log(sousuoparams);

  // return

  // 名称格式化

  if (sousuoparams.mingcheng != "") {
    cqlstr += `desc like '%${sousuoparams.mingcheng}%' `;
  }
  // 层级
  // resolution <=500 AND resolution > 300

  if (sousuoparams.cengji.length != 0) {
    let minlevel = Math.min(...sousuoparams.cengji);
    let minlevelval = Common.getResolutionByLevel(minlevel);
    if (cqlstr == "") {
      cqlstr += `resolution <=${minlevelval} `;
    } else {
      cqlstr += `AND resolution <=${minlevelval} `;
    }

    params.level = sousuoparams.cengji.join(",");
  }
  // 区域范围
  // `BBOX(linerange,${bboxstr},'EPSG:4326') AND${searchresolutionstr}`;
  if (sousuoparams.quyufanweival.length != 0) {
    let tmpitemlon = [];
    let tmpitemlat = [];
    sousuoparams.quyufanweival.map(item => {
      item.features[0].geometry.coordinates[0].map(iitem => {
        tmpitemlon.push(iitem[0]);
        tmpitemlat.push(iitem[1]);
      });
    });
    let bboxstr = `${Math.min(...tmpitemlon)},${Math.min(...tmpitemlat)},${Math.max(
      ...tmpitemlon
    )},${Math.max(...tmpitemlat)}`;
    if (cqlstr == "") {
      cqlstr += `BBOX(linerange,${bboxstr},'EPSG:4326') `;
    } else {
      cqlstr += `AND BBOX(linerange,${bboxstr},'EPSG:4326') `;
    }
  }

  // 时间范围
  // timestamp BETWEEN '2023-01-01T00:00:00Z' AND '2023-12-31T23:59:59Z'
  if (sousuoparams.shijianfanwei.length != 0) {
    params.timeRange = sousuoparams.shijianfanwei.join(":");
    if (cqlstr == "") {
      cqlstr += `imgtime BETWEEN '${sousuoparams.shijianfanwei[0]}' AND '${sousuoparams.shijianfanwei[1]}' `;
    } else {
      cqlstr += `AND imgtime BETWEEN '${sousuoparams.shijianfanwei[0]}' AND '${sousuoparams.shijianfanwei[1]}' `;
    }
  }

  params["CQL_FILTER"] = cqlstr;

  // maxFeatures: pageSize.value,
  // startIndex: pageSize.value * (pageNum.value - 1),
  // sortBy: "imgtime D",

  cqlsearchparams = params;

  loadData();
}

function loadData() {
  // maxFeatures: pageSize.value,
  // startIndex: pageSize.value * (pageNum.value - 1),
  // sortBy: "imgtime D",

  let params = cqlsearchparams;

  params["maxFeatures"] = pageSize.value;
  params["startIndex"] = pageSize.value * (pageNum.value - 1);
  params["sortBy"] = "imgtime D";

  apiList.shujuguanli.getYingxiangList(params).then(res => {
    // console.log(res);
    // isloading.value = false;
    // dataList.value = res.data;
    let tmpdata = [];

    tmpdata = res.features.map(item => {
      return {
        ...item.properties,
        item: item,
      };
    });
    dataList.value = tmpdata;
    totalCount.value = res.totalFeatures;

    Common.removeAlls();
    Common.removeAll();
    Common.loadsearchrectangle(res).then(res => {
      allelist = res.entities.values;
      // viewer.flyTo(res)
    });
  });
}

onMounted(() => {
  apiList.getAttributeSensor().then(res => {
    chuanganqiopts.value = res.data;
  });
});

function closewindow() {
  Common.removeAll();
  Common.removeAlls();
}

defineExpose({
  closewindow,
});
</script>
<style lang="scss" scoped>
.resultlist {
  // height: calc(100% - 135px);
  height: calc(100%);
}

.searchresultitem {
  box-sizing: border-box;
  margin: 5px 0px;
  position: relative;
  padding-left: 50px;
  &:hover {
    background-color: #fff5;
  }
}

.custom-thumbnail {
  .el-image__inner {
    width: 30px !important;
  }
}

.searchcondition {
  // border: ;
  border: 1px solid white;
  padding: 10px;
  // cursor: pointer;
  // margin: 10px;
  box-sizing: border-box;
  border-radius: 5px;
}

.taskcreatecom {
  box-sizing: border-box;
  padding: 10px;
  height: 100%;
  // display: flex;
}
</style>
